var MagicValidatingForm = Class.create({  
  initialize: function(form) {
    this.validity = true;
    form.select('.login-field').invoke('observe', 'blur', this.validateAsLogin);
    form.select('.email-field').invoke('observe', 'blur', this.validateAsEmail.bindAsEventListener(this));
    form.select('.password-field').invoke('observe', 'blur', this.validateAsPassword.bindAsEventListener(this));
    form.select('.password-confirmation-field').invoke('observe', 'blur', this.validateAsPasswordConfirmation.bindAsEventListener(this));
    form.select('input[type="submit"]').invoke('observe', 'click', this.validateAsValidFields.bindAsEventListener(this));
  },
  
  validateAsLogin: function() {
    console.log(this);
    // Don't want have a username that is already taken - use AJAX 
  },
  
  validateAsEmail: function(event) {
    if (!event.target.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|edu)\b/)) {
         var errorForm = $$('.emailFormErrors').first();
         errorForm.setStyle({'display': 'block'})
         this.validity = false;
    }
    else {
         var errorForm = $$('.emailFormErrors').first();
         errorForm.setStyle({'display': 'none'});
         this.validity = true;
    }
  },
  
  validateAsPassword: function(event) {
    if (!event.target.value.match(/(?=.{6,}).*/)) {
              //alert('This password is not strong enough');
              var errorForm = $$('.passwordFormErrors').first();
              errorForm.setStyle({'display': 'block'}) 
              this.validity = false;
            }
            else {
              var errorForm = $$('.passwordFormErrors').first();
              errorForm.setStyle({'display': 'none'});
              this.validity = true;
            }
  },
  
  validateAsPasswordConfirmation: function(event) {
    if (event.target.value !== event.target.up('form').down('.password-field').value) {
              var errorForm = $$('.passwordConfirmationFormErrors').first();
              errorForm.setStyle({'display': 'block'})  
              this.validity = false;
            }
            else {
              var errorForm = $$('.passwordConfirmationFormErrors').first();
              errorForm.setStyle({'display': 'none'});
              this.validity = true;
            }
  },
  
  validateAsValidFields: function(event) {
    event.stop();
    if (this.validity !== true){
      alert('There are errors in the form, correct them then try again');
    }
    else {
      event.target.up('form').submit();
    }
  }
})